/**
 * main.cpp - TestOcr
 * @author 张伟
 * @date 2013/11/27
 */
#include <unistd.h>
#include <tesseract/baseapi.h>
#include <tesseract/strngs.h>

inline void ShowErr(const char* txt)
{
	printf("err: %s\n", txt);
}

//bool GetDataPath(char* datapath, const char* arg0)
//{
//	if (arg0[0] == '/')
//	{
//		const char* path = strrchr(arg0, '/');
//		strncpy(datapath, arg0, path - arg0);
//	}
//	const char* path = strrchr(arg0, '/');
//	return true;
//}

int OcrProcess(const char* infile, const char* outfile, const char* datapath)
{
	tesseract::TessBaseAPI api;
	STRING text_out;
	api.Init(datapath, "chi_sim");
	//api.Init("", "chi_sim+chi_tra");
	//api.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
	//api.SetVariable("tessedit_char_whitelist", "0123456789");
	if (api.ProcessPages(infile, NULL, 0, &text_out) == true)
	{
		if (outfile != NULL && outfile[0] != 0)
		{
			FILE* fp = fopen(outfile, "wb+");
			if (fp != NULL)
			{
				fwrite(text_out.string(), 1, text_out.length(), fp);
				fclose(fp);
			}
			else
			{
				ShowErr("输出文件失败！");
				return -1;
			}
		}
		else
		{
			printf("%s\n", text_out.string());
		}
		return 0;
	}
	else
	{
		ShowErr("调用OCR-API接口转换失败！");
		return -1;
	}
}

int main(int argc, const char* argv[])
{
	if (argc < 2)
	{
		ShowErr("参数数量不正确！请指明要识别的图片文件（及输出的文本文件）！");
		return -1;
	}
	const char* infile = argv[1];
	const char* outfile = NULL;
	if (argc > 2)
		outfile = argv[2];

	char datapath[255] = {0};
	readlink("/proc/self/exe", datapath, 255);
	char* last = strrchr(datapath, '/');
	if (last != NULL)
		last[0] = '\0';
//	GetDataPath(datapath, argv[0]);

	return OcrProcess(infile, outfile, datapath);
}

